#!/usr/bin/python

######################################################
#
# Read in summary of all storms in a year and separate into different
# files for different months.
#
######################################################

#
# MODULES
#
import sys
import os
import string

import math
import warnings

infilename = 'traj_stat_summary'

if len(sys.argv) < 2:
    print 'Usage: %s <summary file>' % sys.argv[0]
    print
    raise SystemExit
else:
    infilename = sys.argv[1]

# open summary file
assert os.path.exists(infilename),"split_summary_monthly: file not found"
try:
    fin = open(infilename, 'r')
except IOError:
    print >> sys.stderr, "split_summary_monthly: could not open %s" % infilename
    exit


# ignore header line
line = fin.readline()
header = string.split(line)

# flag for whether there is currently a file open for writing
outfilename = ''
curmonth = 0

line = fin.readline()
while line:
    elems = string.split(line)
    month = int(elems[2])

    # check if current month matches current open file
    if not (month == curmonth):
        # close current open file, if it exists
        if os.path.exists(outfilename):
            fout.close()

        # open new file for current month
        curmonth = month
        outfilename = '%s_%s' % (infilename, month)
        fout = open(outfilename, 'w')

        # write header
        print >> fout, ' '.join(header)

    # write to current open file
    print >> fout, ' '.join(elems)

    # read next line
    line = fin.readline()
    
    
